<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<meta name="decorator" content="default"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>upload</title><script src="${ctxStatic}/jquery/jquery-1.8.3.min.js" type="text/javascript"></script>
<link href="${ctxStatic}/file-tool/uploadify/upload/system.css" rel="stylesheet" type="text/css" />
<script  src="${ctxStatic}/file-tool/uploadify/upload/system.js" type="text/javascript"></script>
<link href="${ctxStatic}/file-tool/uploadify/3.2.1/uploadify.css" rel="stylesheet" type="text/css" />
<script src="${ctxStatic}/file-tool/uploadify/3.2.1/jquery.uploadify.js" type="text/javascript" ></script>
<script type="text/javascript">
var uploadAction = "${ctxStatic}/file/connector;JSESSIONID=${pageContext.session.id}";//;JSESSIONID=${pageContext.session.id}
var fileId = '${param.fileId}'; 
var dialogId = '${param.dialogId}';
var targetId = '${param.targetId}';
var callback = '${param.callback}';
var isAuto = false;
var fileSize = 1024*500;
var fileTypeDesc = "视频文件";
//var fileTypeExts = null;//
var fileTypeExts = '*.*';
var fileUri = '${fns:getConfig("aliyuncs.fileUri")}';
var uid = '${param.uid}';
var isStopLoad = true;
var serverType = '${param.serverType}';
var bucketName = '${param.bucketName}';
var uploadType = 'simpleFileUpload';

function startUpload(){
	var key = jQuery("#fileKey").val();
	if(key == null || key == ''){
		alert("key 为空！");
		return ;
	}
	if(key.indexOf('/')==-1){
		alert("key 必须包含文件夹 如 ： test/file2017.txt  ！");
		return ;
	}
	var formData = {key : key};
	jQuery('#uploadify').uploadify('settings','formData',formData);
	jQuery('#uploadify').uploadify('upload','*');
}
function cancel(){
	jQuery('#uploadify').uploadify('cancel','*');
	//jQuery('#'+dialogId,parent.document).remove();
	parent.closeWindows(dialogId)
}

function init(){
	var currentFilePath = null;
	if(currentFilePath == null){
		currentFilePath = '/test';
	}
	var date = new Date(), year = date.getFullYear(), month = (date.getMonth()+1)>9?date.getMonth()+1:"0"+(date.getMonth()+1);
	var currentFolder = currentFilePath+"/"+year+"/"+month+"/";
	var filetype = null;
	if(filetype == null){
		filetype = 'files';
	}
	if(uid == null || uid == ''){
		uid = 'file'+Math.round(Math.random()*Math.pow(10,10));
	}
	uploadAction = addUrlParam(uploadAction,'type',filetype);
	uploadAction = addUrlParam(uploadAction,'currentFolder',currentFolder);
	uploadAction = addUrlParam(uploadAction,'langCode','zh-cn');
	uploadAction = addUrlParam(uploadAction,'prefix',currentFolder);
	
	
	//var fileSize = Math.round(settings.fileSizeLimit / 1024)*1024;
	var suffix   = 'KB';
	var size = Math.round(fileSize / 1024)*1000;
	if (size > 1000) {
		size = Math.round(size / 1000);
		suffix   = 'MB';
	}
	var fileSizeParts = size.toString().split('.');
	var showFileSize = fileSizeParts[0];
	if (fileSizeParts.length > 1) {
		showFileSize += '.' + fileSizeParts[1].substr(0,2);
	}
	showFileSize += suffix;
	var info = '最大尺寸'+showFileSize;
	jQuery('#').html(info);
	if(isAuto){
		jQuery('[name="uploadButton"]').css('display','none');
	}
}

</script>

<script type="text/javascript">
var st = DateFormat(new Date(),'yyyyMMddHHmmss');
	$(function() { 
		init(); //debugger;
		if(serverType == null || serverType == ''){
			serverType = 'qiniu';
			//alert("serverType is null");
		}
		var script= uploadAction ;
		script = addUrlParam(script,'command','FileUpload');
		script = addUrlParam(script,'uid',uid);
		script = addUrlParam(script,'serverType',serverType);
		script = addUrlParam(script,'bucketName',bucketName);
		script = addUrlParam(script,'uploadType',uploadType);
		
		var formData = {};
		var percentagecount = 0;
        $("#uploadify").uploadify({
           	// Required Settings
            'swf': '${ctxStatic}/file-tool/uploadify/3.2.1/uploadify.swf',
            'uploader': script,
			
			// Options
			auto            : isAuto,              // Automatically upload files when added to the queue
			buttonClass     : '',                 // A class name to add to the browse button DOM object
			buttonCursor    : 'hand',             // The cursor to use with the browse button
			buttonImage     : null,                 // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
			buttonText      : 'SELECT',           // The text to use for the browse button
			checkExisting   : false,              // The path to a server-side script that checks for existing files on the server
			debug           : false,              // Turn on swfUpload debugging mode
			fileObjName     : 'Filedata',         // The name of the file object to use in your server-side script
			fileSizeLimit   : fileSize,                  // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
			fileTypeDesc    : fileTypeDesc==null?'All File' :  fileTypeDesc,        // The description for file types in the browse dialog
			fileTypeExts    : fileTypeExts==null?"*.*": fileTypeExts,              // Allowed extensions in the browse dialog (server-side validation should also be used)
			height          : 30,                 // The height of the browse button
			itemTemplate    : false,              // The template for the file item in the queue
			method          : 'post',             // The method to use when sending files to the server-side upload script
			multi           : false,               // Allow multiple file selection in the browse dialog
			formData        : formData,                 // An object with additional data to send to the server-side upload script with every file upload
			preventCaching  : true,               // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
			progressData    : 'percentage',       // ('percentage' or 'speed') Data to show in the queue item during a file upload
			queueID         : 'uploadifyqueue',              // The ID of the DOM object to use as a file queue (without the #)
			queueSizeLimit  : 5,                // The maximum number of files that can be in the queue at one time
			removeCompleted : false,               // Remove queue items from the queue when they are done uploading
			removeTimeout   : 30000,                  // The delay in seconds before removing a queue item if removeCompleted is set to true
			requeueErrors   : false,              // Keep errored files in the queue and keep trying to upload them
			successTimeout  : 600000,                 // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
			uploadLimit     : 5,                  // The maximum number of files you can upload
			width           : 80,                // The width of the browse button
            onCancel : function(file) {
         			 //alert('The file ' + file.name + ' was cancelled.');
    		},
    		//this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize
       		onUploadProgress: function(file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded,uploadSize){ //
       			var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
       			var html = null;
       			if(percentage == 0){
       				html = '<div class="righttag">正在加载...</div>';
       			}else{
       				html ='<div class="righttag">正在加载'+percentage+'%</div>';
       			}
       			$('#' + file.id).find('.data').html(html);
       		},
			onUploadSuccess : function(file, data, response){
				//console.info("--已完成--"+data);
				isStopLoad = true;
				if(data==null){
					return false;
				}
				var fileObjId = file.id;
    			var fileObj = jQuery('#'+fileObjId);
    			var cancelObj = fileObj.children('.cancel');
    			fileObj.children('.data').html('--已完成');
    			cancelObj.html('<a ></a>');
    			var aObj = cancelObj.children('a');
    			aObj.css('background-image','none');
    			aObj.css('text-indent','-30px');
    			aObj.css('width','50px');
    			$('#' + file.id).find('.uploadify-progress-bar').css('width', 100 + '%');
	    		var functionName = "parent."+callback+"()";
	    		eval(functionName);
    			cancel(); //关闭窗口
			},
			onUploadStart : function(file){
				//var funcName = 'loadReed("'+file.id+'",'+'"'+file.name+'",'+0+')';
				//setTimeout(funcName, 1000);
				//var fileObj =  $('#' + file.id);
				//fileObj.find('.data').html('<div class="righttag">正在加载...</div>');
				isStopLoad = false;
				//loadReed(file.id,file.name,0);
			}
			,onUploadError : function(file, errorCode, errorMsg,errorString){
				//console.info("--errorMsg--"+errorMsg);
				//isStopLoad = true;
			}
			,overrideEvents  : ['onUploadProgress','onUploadSuccess']
          });
      });  
	
	function loadReed(id,name,percentage){
		if(name==null || name == '' || isStopLoad == true){
			return ;
		}
		var fileName = encodeURI(name);
		var data = {'fileName': fileName ,uid : uid};
		var urls = addUrlParam(uploadAction,'command','getBigFile');
		jQuery.ajax({  
			url: urls, async : true,type: "POST",dataType : 'json',
			data : data,
			success: function(response) {
				var info = response;
				percentage = info.percentage;
				var fileObj =  $('#' + id);
				var progress = fileObj.find('.uploadify-progress-bar');
				if(percentage<100){ //&& fileObj.find('.data').html()!='--已完成'
					if(0 == percentage){
						//fileObj.find('.data').html('<div class="righttag">正在加载...</div>');
						//fileObj.find('.data').html('开始上传');
					}else{
						fileObj.find('.data').html(' - ' + percentage + '%');
						progress.css('width', percentage + '%');
					}
					setTimeout('loadReed("'+id+'",'+'"'+name+'",'+percentage+')', 1000);
				}else if(percentage == 100){
	    			fileObj.children('.data').html('--已完成');
	    			var cancelObj = fileObj.children('.cancel');
	    			cancelObj.html('<a ></a>');
	    			var aObj = cancelObj.children('a');
	    			aObj.css('background-image','none');
	    			aObj.css('text-indent','-30px');
	    			aObj.css('width','50px');
	    			fileObj.find('.uploadify-progress-bar').css('width', 100 + '%');
	    			if(parent.updateFilePath!=null){ //执行上级页面脚本
						parent.updateFilePath(fileId,info.url);
					}else{
						var functionName = "parent."+fileId+'FinderOpen()';
						eval(functionName);
					}
	    			cancel(); //关闭窗口
				}
			},
			error: function(e){console.error(e);}
		});
	}
	
	function DateFormat(date , fmt){
		  var o = {
			"M+" : date.getMonth() + 1, //月份   
			"d+" : date.getDate(), //日   
			"h+" : date.getHours(), //小时   
			"H+" : date.getHours(), //小时  
			"m+" : date.getMinutes(), //分   
			"s+" : date.getSeconds(), //秒   
			"q+" : Math.floor((date.getMonth() + 3) / 3), //季度   
			"S" : date.getMilliseconds() //毫秒   
		};
		if (/(y+)/.test(fmt)){
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for ( var k in o){
			if (new RegExp("(" + k + ")").test(fmt)){
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]): (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;   
	}
  </script>
  <style type="text/css">
  	.righttag{
		  top: 5px;
		  right: 10px;
		  width: 100px;
		  height: 20px;
		  line-height: 20px;
		  background: #f8f8f8 url(smallloader.gif) no-repeat 8px center;
		  border: 1px solid #ddd;
		  padding-left: 30px;
		  font-size: 11px;
		  color: #888;
		  z-index: 9999;
  	}
  </style>
  
</head>
<body>
<!-- <input type="button" name="getUploadButton" value="获取文件信息" onclick="getFileinfo()">
 -->
	<div class="uploadDiv" style="height: 350px;">
		<!-- 文件上传Table  -->
		<table class="uploadTable" style="height: 300px;">
			<!-- 标题区域 -->
			<tr class="uploadTitle" style="height: 100px;">
				<td colspan="3">
					<div class="uploadTitleDiv" style="text-align: left;font-size: 11px;line-height:26px;height: 100px;padding-left: 10px;">
						<span id="filesizeid">
							<label>云存储 Key (必须包含文件夹  如 ： test/file.txt): </label> <br>
							<input id="fileKey" type="text" value="" 
							style="width: 320px;height: 30px;">
						</span>
						<!-- 附件上传  jQuery插件版本 ： uploadfy3.2.1-->
					</div>
				</td>
			</tr>
			<!-- 文件区域 -->
			<tr class="uploadList" style="height:200px;">
				<td colspan="3">
					<div class="uploadListDiv" id="uploadifyqueue" style="height:200px;background-color: #FFFFFF;">
						
					</div>
				</td>
			</tr>
			<!-- 按钮区域 -->
			<tr class="uploadButton">
				<td class="uploadButtonleft">
					<div class="uploadButtonImg">
						<!-- <input type="button" value="选择文件"> -->
						<input type="file" name="uploadify" id="uploadify"/>
					</div>
				</td>
				<td class="uploadButtonCenter">
					<input type="button" name="uploadButton" value="上传" onclick="startUpload()">
				</td>
				<td class="uploadButtonRight">
					<input type="button"  value="关闭" onclick="cancel()">
					<!-- <input type="button" value="获取文件" onclick="getFileinfo()"> -->
				</td>
			</tr>
		</table>
	</div>

</body>
</html>
